package cn.com.czpb.client.module.personal.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.BaseFragment;
import cn.com.czpb.client.custorm.RecycleViewDivider;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.usercenter.MessageBean;
import cn.com.czpb.client.model.usercenter.MessageEntity;
import cn.com.czpb.client.module.news.activity.NewsAlbum_Activity;
import cn.com.czpb.client.module.news.activity.NewsDetailActivity;
import cn.com.czpb.client.module.news.activity.NewsVideoActivity;
import cn.com.czpb.client.module.news.dialog.ReplyDialog;
import cn.com.czpb.client.module.personal.adapter.MessageAdapter;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.AAnim;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/8/8.
 */

public class MessageFragment extends BaseFragment implements OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener,
        BaseQuickAdapter.OnItemChildClickListener {
    @BindView(R.id.swipe_layout)
    SmartRefreshLayout swipe_layout;
    @BindView(R.id.recycler_message)
    RecyclerView recyclerView;
    MessageAdapter adapter;
    private List<MessageBean> list;
    int Page = 1;
    int PageSize = 15;
    boolean mFlagRefresh;


    @Override
    public int setMyContentView() {
        return R.layout.fragment_message;
    }

    public static MessageFragment newInstance() {
        MessageFragment messageFragment = new MessageFragment();
        return messageFragment;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        init();
    }

    public void init() {
        list = new ArrayList<>();
        adapter = new MessageAdapter(list, activity);
        LinearLayoutManager manager = new LinearLayoutManager(activity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        initList();
        recyclerView.setLayoutManager(manager);
        int height = (int) getResources().getDimension(R.dimen.x2);
        recyclerView.addItemDecoration(new RecycleViewDivider(activity,
                LinearLayoutManager.HORIZONTAL, height,
                getResources().getColor(R.color.color_e8e8e8)));
//        swipe_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                mFlagRefresh = true;
//                Page = 1;
//                initList();
//            }
//        });

        swipe_layout.setRefreshHeader(new ClassHeader_other(activity));
        swipe_layout.setOnRefreshListener(this);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, recyclerView);
        recyclerView.setAdapter(adapter);
    }

    private void ReplyItemClick(BaseQuickAdapter adapter, View view, int position) {
        MessageBean obj = (MessageBean) adapter.getItem(position);
        Intent intent = new Intent();
        intent.putExtra("from", "collection");
        NewsBean nb = new NewsBean();
        nb.setNid(obj.getReplyto().getNid());
        nb.setImgs(obj.getReplyto().getImgs());
        boolean flag = false;//是否是预定类型
        if ("1".equals(obj.getReplyto().getRtype())) {
            intent.putExtra("newbean", nb);
            flag = true;
            intent.setClass(activity, NewsDetailActivity.class);
        } else if ("2".equals(obj.getReplyto().getRtype())) {
            intent.putExtra("newbean", nb);
            intent.putExtra("rvalue", obj.getReplyto().getNid());
            flag = true;
            intent.setClass(activity, NewsAlbum_Activity.class);
        } else if ("4".equals(obj.getReplyto().getRtype())) {
            intent.putExtra("newbean", nb);
            flag = true;
//            intent.setClass(activity, NewsZhuanTiActivity.class);
        } else if ("6".equals(obj.getReplyto().getRtype())) {
            intent.putExtra("newbean", nb);
            flag = true;
            intent.setClass(activity, NewsVideoActivity.class);
        }
        if (flag) {
            startActivity(intent);
            AAnim.startScreen(activity);
        }


    }


    private void initList() {
        Map<String, String> map = new HashMap<>();
        map.put("Page", Page + "");
        map.put("PageSize", PageSize + "");
        map.put("uid", spu.getUser().getUid());
        Factory.provideHttpService().my_message(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<MessageEntity, Boolean>() {
                    @Override
                    public Boolean call(MessageEntity notifiEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<MessageEntity>() {
                    @Override
                    public void call(MessageEntity notifiEntity) {
                        LogUtils.e("code--" + notifiEntity.code);
                        LogUtils.e("code--" + notifiEntity.msg);
                        if (mFlagRefresh) {
                            swipe_layout.finishRefresh();

                        }
                        if ("200".equals(notifiEntity.code)) {

                            setListData(notifiEntity.data);

                            adapter.notifyDataSetChanged();

                            LogUtils.e(list.size() + "");
                        } else if (!mFlagRefresh) {
                            Page--;
                        }

                        mFlagRefresh = false;
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable--" + throwable.getMessage());
                    }
                });


    }

    @Override
    public void onLoadMoreRequested() {
        Page++;
        initList();

    }

    public void setListData(List<MessageBean> list) {
        if (mFlagRefresh) {
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < PageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        final MessageBean obj = (MessageBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.tv_title:

                ReplyItemClick(adapter, view, position);
                break;
            case R.id.reply_message:
                ReplyDialog dialog = new ReplyDialog(activity, R.style.ChangeNamedialog, new ReplyDialog.InputListener() {
                    @Override
                    public void inputstr(String string) {

                        sendComment(string, obj.getCid(), obj.getReplyto().getNid(), obj.getReplyto().getType());

                    }
                });
                dialog.show();
                break;
        }
    }

    private void sendComment(String content, String cid, String nid, String type) {

        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        map.put("uid", spu.getUser().getUid());
        map.put("type", type);
        map.put("title", nid);
        map.put("content", content);
        map.put("cid", cid);
        map.put("json_url", "fsdfsdfsfs");//随便传一个
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity entity) {

                        if ("200".equals(entity.code)) {
                            TUtils.toast("评论成功");
//                            et_reply.setText("");
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                            setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");

                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                mFlagRefresh = true;
                Page = 1;
                initList();
            }
        },2000);
    }
}
